﻿using System;

public static class DataGridExtension
{
    public static DataGridCell GetCell(this DataGrid dataGrid, int row, int column)
    {
        try
        {
            var dataGridRow = dataGrid.GetRow(row);
            if (null != dataGridRow)
            {
                var visualChild = VisualHelper.GetVisualChild<DataGridCellsPresenter>(dataGridRow);
                var cell = visualChild?.ItemContainerGenerator?.ContainerFromIndex(column) as DataGridCell;

                if (null == cell)
                {
                    dataGrid.ScrollIntoView(dataGridRow, dataGrid.Columns[column]);
                    cell = visualChild?.ItemContainerGenerator?.ContainerFromIndex(column) as DataGridCell;
                }

                return cell;
            }
        }
        catch (System.Exception)
        {
            throw;
        }
    }
    /// <summary>
    /// 获取 DataGrid　中指定的行
    /// </summary>
    /// <param name="dataGrid">DataGrid</param>
    /// <param name="rowIndex">行</param>
    /// <returns></returns>
    public static DataGridRow GetRow(this DataGrid dataGrid, int rowIndex)
    {
        dataGrid.UpdateLayout();

        var row = dataGrid.ItemContainerGenerator.ContainerFromIndex(rowIndex) as DataGridRow;

        if (null == row)
        {
            dataGrid.UpdateLayout();
            dataGrid.ScrollIntoView(dataGrid.Items[rowIndex]);

            row = dataGrid.ItemContainerGenerator.ContainerFromIndex(rowIndex) as DataGridRow;
        }

        return row;
    }
}

public class VisualHelper
{
    public static T GetVisualChild<T>(Visual parent) where T : Visual
    {
        T t = default(T);
        int childrenCount = VisualTreeHelper.GetChildrenCount(parent);
        for (int childIndex = 0; childIndex < childrenCount; childIndex++)
        {
            //如果是自己写此代码，容易出错
            var child = VisualTreeHelper.GetChild(parent, childIndex) as Visual;
            t = child as T;
            if (null == t)
            {
                t = GetVisualChild<T>(child);
            }

            if (null != t)
            {
                break;
            }
        }
        return t;
    }
}